package com.example.qxfw.qxybzz.service.Impl;


import com.example.qxfw.dysjrh.config.DmgisConfig;
import com.example.qxfw.qxybzz.entity.vo.ImageFile;
import com.example.qxfw.qxybzz.service.WarningMediaService;
import com.mongodb.client.DistinctIterable;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.http.HttpHeaders;
import org.springframework.http.HttpStatus;
import org.springframework.http.MediaType;
import org.springframework.http.ResponseEntity;
import org.springframework.stereotype.Service;

import javax.imageio.ImageIO;
import java.awt.*;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;
import java.io.IOException;
import java.io.InputStream;
import java.util.ArrayList;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Service
@RequiredArgsConstructor
public class WarningMediaServiceImpl implements WarningMediaService {


    @Qualifier("mongoPrimaryTemplate")
    @Autowired
    private MongoTemplate mongoTemplate;

    private final DmgisConfig dmgisConfig;


    @Override
    public List<String> getWarningMediaName() {
//        DistinctIterable<String> distinct = mongoTemplate.getCollection("image_file").distinct("name", String.class);
//        List<String> names = new ArrayList<>();
//        for (String name : distinct) {
//            names.add(name);
//        }
        //或者：
        Query query = new Query();
        List<ImageFile> imageFiles = mongoTemplate.find(query, ImageFile.class);
        List<String> names = imageFiles.stream()
                .map(ImageFile::getName)
                .collect(Collectors.toList());
        return names;
    }

    /**
     * 根据图片描述获取图片（根据模版库中的名字获取指定模版指定图片）
     *
     * @param text
     */
    @Override
    public ResponseEntity<byte[]> getImageByName(String text) {
        Query query = new Query();
        query.addCriteria(Criteria.where("name").is(text));
        ImageFile imageFile = mongoTemplate.findOne(query, ImageFile.class);
        if (imageFile == null) {
            // 如果没有找到对应的图片文件，返回404 Not Found
            return ResponseEntity.notFound().build();
        }
        byte[] data = imageFile.getData();

        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);

        return ResponseEntity.ok()
                .headers(headers)
                .body(data);
    }

    /**
     * 根据实况信息，预报信息，措施建议，图片编号，是否展示等值图，返回图片
     *
     * @param skcontent
     * @param ybcontent
     * @param csjycontent
     * @param imageId
     * @param isShowImage
     */
    @Override
    public ResponseEntity<byte[]> getImage2(String skcontent, String ybcontent, String csjycontent, String imageId, Integer isShowImage, String name) {
        if (imageId == null) {
            log.warn("Image ID is null");
            return ResponseEntity.notFound().build();
        }
        Query query = new Query();
        query.addCriteria(Criteria.where("_id").is(imageId));
        ImageFile imageFile = mongoTemplate.findOne(query, ImageFile.class);

        //获取气象图
        Query query1 = new Query();
        query1.addCriteria(Criteria.where("name").is(name));
        ImageFile one = mongoTemplate.findOne(query1, ImageFile.class);
        if (one == null) {
            log.warn("Image file not found for ID: {}", imageId);
            return ResponseEntity.notFound().build();
        }
        byte[] qxdata = one.getData();

        if (imageFile == null) {
            log.warn("Image file not found for ID: {}", imageId);
            return ResponseEntity.notFound().build();
        }

        byte[] data = imageFile.getData();


        String productname = dmgisConfig.getProductname();
        try {
            //加标题
            data = overlayTextOnImage(data, productname);
            data = overlayTextOnImage2(data, "气象服务信息");
        } catch (IOException e) {
            e.printStackTrace();
        }
        //判断是否需要等制图
        if (isShowImage == 1) {
            //叠加等值图片
            data = overlayImages(data, qxdata);
        }

        byte[] bytes = data;
        if (skcontent != null) {
            try {
                bytes = overlayTextOnImage3(bytes, "实况信息");
                bytes = overlayTextOnImage4(bytes, skcontent);
            } catch (IOException e) {
                log.error("Failed to overlay skcontent on image", e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to overlay skcontent on image".getBytes());
            }
        }
        if (ybcontent != null) {
            try {
                bytes = overlayTextOnImage5(bytes, "预报信息");
                bytes = overlayTextOnImage6(bytes, ybcontent);
            } catch (IOException e) {
                log.error("Failed to overlay ybcontent on image", e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to overlay ybcontent on image".getBytes());
            }
        }
        if (csjycontent != null) {
            try {
                bytes = overlayTextOnImage7(bytes, "措施建议");
                bytes = overlayTextOnImage8(bytes, csjycontent);
            } catch (IOException e) {
                log.error("Failed to overlay csjycontent on image", e);
                return ResponseEntity.status(HttpStatus.INTERNAL_SERVER_ERROR).body("Failed to overlay csjycontent on image".getBytes());
            }
        }
        HttpHeaders headers = new HttpHeaders();
        headers.setContentType(MediaType.IMAGE_JPEG);
        return ResponseEntity.ok().headers(headers).body(bytes);
    }


    public byte[] overlayTextOnImage(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 40);
            g2d.setFont(font);
            g2d.setColor(Color.blue); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getAscent();

            double ratio = 0.04; // 比例
            int y = (int) (originalImage.getHeight() * ratio);
            int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage2(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 50);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getAscent();

            double ratio = 0.08; // 比例
            int y = (int) (originalImage.getHeight() * ratio);
            int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage3(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 35);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getAscent();

            double ratio = 0.13; // 比例
            int y = (int) (originalImage.getHeight() * ratio);
            int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage4(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 30);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为黑色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textHeight = metrics.getAscent();

            // 每行字符数
            int charsPerLine = 40;

            // 分割文字
            List<String> lines = new ArrayList<>();
            for (int i = 0; i < text.length(); i += charsPerLine) {
                int end = Math.min(i + charsPerLine, text.length());
                lines.add(text.substring(i, end));
            }

            // 计算起始y位置
            double ratio = 0.18; // 比例
            int y = (int) (originalImage.getHeight() * ratio);

            // 设置行间距
            int lineSpacing = 20; // 可以根据需要调整行间距

            // 绘制每一行文本
            for (String line : lines) {
                int textWidth = metrics.stringWidth(line);
                int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中
                g2d.drawString(line, x, y);
                y += textHeight + metrics.getDescent() + lineSpacing; // 移动到下一行，增加行间距
            }

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage5(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 35);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getAscent();

            double ratio = 0.75; // 比例
            int y = (int) (originalImage.getHeight() * ratio);
            int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage6(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 28);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为黑色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textHeight = metrics.getAscent();

            // 每行字符数
            int charsPerLine = 35;

            // 分割文字
            List<String> lines = new ArrayList<>();
            for (int i = 0; i < text.length(); i += charsPerLine) {
                int end = Math.min(i + charsPerLine, text.length());
                lines.add(text.substring(i, end));
            }

            // 计算起始y位置
            double ratio = 0.8; // 比例
            int y = (int) (originalImage.getHeight() * ratio);

            // 设置行间距
            int lineSpacing = 18; // 可以根据需要调整行间距

            // 绘制每一行文本
            for (String line : lines) {
                int textWidth = metrics.stringWidth(line);
                int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中
                g2d.drawString(line, x, y);
                y += textHeight + metrics.getDescent() + lineSpacing; // 移动到下一行，增加行间距
            }

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage7(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 35);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为红色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textWidth = metrics.stringWidth(text);
            int textHeight = metrics.getAscent();

            double ratio = 0.9; // 比例
            int y = (int) (originalImage.getHeight() * ratio);
            int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中

            // 绘制文本
            g2d.drawString(text, x, y);

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public byte[] overlayTextOnImage8(byte[] imageBytes, String text) throws IOException {
        try (InputStream inputStream = new ByteArrayInputStream(imageBytes)) {
            BufferedImage originalImage = ImageIO.read(inputStream);

            // Create a graphics context to draw the text
            Graphics2D g2d = originalImage.createGraphics();

            // 设置抗锯齿以提高文本质量
            g2d.setRenderingHint(RenderingHints.KEY_ANTIALIASING, RenderingHints.VALUE_ANTIALIAS_ON);

            // 设置字体和颜色
            Font font = new Font("SansSerif", Font.BOLD, 28);
            g2d.setFont(font);
            g2d.setColor(Color.black); // 设置字体颜色为黑色

            // 计算文本的位置（居中）
            FontMetrics metrics = g2d.getFontMetrics();
            int textHeight = metrics.getAscent();

            // 每行字符数
            int charsPerLine = 35;

            // 分割文字
            List<String> lines = new ArrayList<>();
            for (int i = 0; i < text.length(); i += charsPerLine) {
                int end = Math.min(i + charsPerLine, text.length());
                lines.add(text.substring(i, end));
            }

            // 计算起始y位置
            double ratio = 0.92; // 比例
            int y = (int) (originalImage.getHeight() * ratio);

            // 设置行间距
            int lineSpacing = 15; // 可以根据需要调整行间距

            // 绘制每一行文本
            for (String line : lines) {
                int textWidth = metrics.stringWidth(line);
                int x = (originalImage.getWidth() - textWidth) / 2; // 文本水平居中
                g2d.drawString(line, x, y);
                y += textHeight + metrics.getDescent() + lineSpacing; // 移动到下一行，增加行间距
            }

            // 释放图形上下文资源
            g2d.dispose();

            // 将修改后的图像写入字节数组输出流
            try (ByteArrayOutputStream outputStream = new ByteArrayOutputStream()) {
                ImageIO.write(originalImage, "png", outputStream);
                return outputStream.toByteArray();
            }
        }
    }

    public static byte[] overlayImages(byte[] baseImageBytes, byte[] overlayImageBytes) {
        try {
            // 将字节数组转换为BufferedImage
            BufferedImage baseImage = ImageIO.read(new ByteArrayInputStream(baseImageBytes));
            BufferedImage overlayImage = ImageIO.read(new ByteArrayInputStream(overlayImageBytes));

            // 获取底图的宽度和高度
            int baseWidth = baseImage.getWidth();
            int baseHeight = baseImage.getHeight();

            // 设置叠加图像的宽度和高度（比底图小一点）
            int overlayWidth = (int) (baseWidth * 0.98); // 98% of base width
            int overlayHeight = (int) (baseHeight * 0.4); // 40% of base height

            // 计算叠加图像的起始位置（居中）
            int x = (baseWidth - overlayWidth) / 2;
//            int y = (baseHeight - overlayHeight) / 2;
            double ratio = 0.7; // 比例
            int y = (int) (overlayImage.getHeight() * ratio);

            // 获取底图的绘图上下文
            Graphics2D g2d = baseImage.createGraphics();

            // 绘制要叠加的图片
            g2d.drawImage(overlayImage, x, y, overlayWidth, overlayHeight, null);
            g2d.dispose();

            // 将结果转换回字节数组
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ImageIO.write(baseImage, "png", baos);
            return baos.toByteArray();
        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }
    }


}
